package com.nirvana.utils;

import com.nirvana.factory.ItemFactory;
import com.nirvana.item.CommonItem;
import com.nirvana.type.ItemType;
import com.nirvana.ui.SearchFileChooser;

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.io.File;

public class FileUtil {
    public static void chooseFile(JComponent parent, JTextField fileNameTextField, JTextField defClassNameTextField, String[] acceptSuffix, String dir) {
        JFileChooser jFileChooser = new SearchFileChooser();
        jFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        FileFilter fileFilter = new FileFilter() {
            @Override
            public boolean accept(File f) {
                if (f.isDirectory()) return true;
                String fileName = f.getName();
                for (String suffix : acceptSuffix) {
                    if (fileName.endsWith(suffix)) return true;
                }
                return false;
            }

            @Override
            public String getDescription() {
                String join = String.join("/", acceptSuffix);
                return "筛选"+join+"文件";
            }
        };
        jFileChooser.setMultiSelectionEnabled(false);
        jFileChooser.setFileFilter(fileFilter);
        jFileChooser.setCurrentDirectory(new File(dir));
        jFileChooser.showOpenDialog(parent);
        File file = jFileChooser.getSelectedFile();
        if (file != null && file.isFile() && fileFilter.accept(file)) {
            CommonItem commonItem = ItemFactory.getCommonItem(ItemType.DefPropertyItem);
            commonItem.resolve(file);
            fileNameTextField.setText(file.getAbsolutePath());
            defClassNameTextField.setText(commonItem.getDefClassName());
            UIUtil.refresh(parent);
            commonItem.refresh();
        }
    }
}
